"""
Flask中数据库的操作
pip install Flask-SQLAlchemy
"""
import os.path

from flask import Flask, request, make_response, render_template, redirect, url_for
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)  # 创建一个Flask的实例
ctx = app.app_context()  # 创建上下文对象，通过上下文可以访问Flask中全局的对象
ctx.push()  # 将上下文推送到堆栈中
# 数据库的类型+操作数据库的包://用户名:密码@主机地址:端口号/数据库名字
uri = "mysql+pymysql://root:123456@127.0.0.1:3306/flask_test"
app.config['SQLALCHEMY_DATABASE_URI'] = uri
db = SQLAlchemy(app)  # 创建一个操作数据库的对象


# 一个类对应数据库中的一个表
class Member(db.Model):
    __tablename__ = 'member'  # 设置表名
    phone = db.Column(db.String(11), primary_key=True)
    pwd = db.Column(db.String(18))
    amount = db.Column(db.Float)  # 浮点数


# http://127.0.0.1:5000/register?mobilephone=18012345678&pwd=123456
# GET
@app.route("/register", methods=['GET'])
def register():
    phone = request.args.get("mobilephone")
    pwd = request.args.get("pwd")
    # 检查输入的数据是否合法
    # 写到数据库
    m = Member(phone=phone, pwd=pwd, amount=0)
    try:
        db.session.add(m)
        db.session.commit()
        return make_response("注册成功")
    except Exception as e:
        return make_response(f"注册失败，用户名或密码错误，错误信息为：{e}")


@app.route("/login", methods=['POST'])
def login():
    phone = request.form.get("mobilephone")
    pwd = request.form.get("pwd")
    # print(phone, pwd)
    if phone.strip() == "" or pwd.strip() == "":
        return make_response("用户名或密码为空")
    else:
        # 从数据库中查找
        m = Member.query.filter_by(phone=phone).first()
        if m is None:
            return make_response("用户未注册")
        else:
            if pwd == m.pwd:
                res = make_response("登录成功")
                res.set_cookie("logininfo", f"user {phone} is login", max_age=500)
                res.set_cookie("tips", "this is a test")
                return res
            else:
                return make_response("密码错误")


@app.route("/recharge", methods=['POST'])
def recharge():
    phone = request.form.get("mobilephone")
    amount = request.form.get("amount")

    # 校验Cookies
    a = request.cookies.get("logininfo")
    b = request.cookies.get("tips")
    if a == f"user {phone} is login" and b == "this is a test":
        pass
    else:
        return make_response("请先登录")

    if phone.strip() == "":
        return make_response("手机号码为空")
    else:
        m = Member.query.filter_by(phone=phone).first()
        if m is None:
            return make_response("用户未注册")
        else:
            if amount.strip() == "" or float(amount) <= 0:
                return make_response("充值金额不正确")
            else:
                m.amount += float(amount)
                db.session.commit()
                return make_response("充值成功")


@app.route("/withdraw", methods=['POST'])
def withdraw():
    phone = request.form.get("mobilephone")
    amount = request.form.get("amount")

    # 校验Cookies
    a = request.cookies.get("logininfo")
    b = request.cookies.get("tips")
    if a == f"user {phone} is login" and b == "this is a test":
        pass
    else:
        return make_response("请先登录")

    if phone.strip() == "":
        return make_response("手机号码为空")
    else:
        m = Member.query.filter_by(phone=phone).first()
        if m is None:
            return make_response("用户未注册")
        else:
            if amount.strip() == "" or float(amount) <= 0:
                return make_response("取现金额不正确")
            else:
                if m.amount < float(amount):
                    return make_response("账户余额不足")
                else:
                    m.amount -= float(amount)
                    db.session.commit()
                    return make_response("取现成功")


@app.route("/upload", methods=['POST', 'GET'])
def upload():
    if request.method == 'POST':
        f = request.files.get("mf")
        f.save(os.path.join("upload", f.filename))
        return f"文件{f.filename}已经成功上传"
    else:
        return redirect(url_for('upload'))


@app.route('/index')
def index():
    return render_template("index.html")  # 返回一个html的页面


@app.route("/register.html")
def register_html():
    return render_template("register.html")


@app.route("/login.html")
def login_html():
    return render_template("login.html")


@app.route("/recharge.html")
def recharge_html():
    return render_template("recharge.html")


@app.route("/withdraw.html")
def withdraw_html():
    return render_template("withdraw.html")


@app.route("/logout.html")
def logout_html():
    res = make_response("退出登录成功")
    res.delete_cookie("logininfo")
    res.delete_cookie("tips")
    return res


@app.route("/upload.html")
def upload_html():
    return render_template("upload.html")


if __name__ == '__main__':
    # db.drop_all()  # 删除所有表
    # db.create_all()  # 创建表
    # # 表中添加数据    添加数据时，需要带着参数名
    # m1 = Member(phone="18012345678", pwd="123456", amount=1000)
    # m2 = Member(phone="15012345678", pwd="123456", amount=2000)
    # m3 = Member(phone="13012345678", pwd="123456", amount=500.5)
    # db.session.add(m1)  # 添加一个
    # db.session.add_all([m2, m3])  # 添加多个
    # db.session.commit()

    app.run(host="127.0.0.1", port=5000, debug=True)
